package io.rong.callkit.huke;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.SystemClock;

import net.oschina.common.helper.SharedPreferencesHelper;

import io.rong.callkit.huke.Bean.UserInfo;

/**
 * 账户辅助类，
 * 用于更新用户信息和保存当前账户等操作
 */
public final class AccountHelper {

    public static final String USER = "USER_LOGIN";

    public static final String TOKEN = "TOKEN";  //token值

    private static final String TAG = AccountHelper.class.getSimpleName();
    private UserInfo user;
    private Context application;
    @SuppressLint("StaticFieldLeak")
    private static AccountHelper instances;

    private AccountHelper(Context application) {
        this.application = application;
    }

    public static void init(Context application) {
        if (instances == null)
            instances = new AccountHelper(application);
        else {
            // reload from source
            instances.user = SharedPreferencesHelper.loadFormSource(instances.application, UserInfo.class);

        }
    }

     /**
     * 保存登陆信息
     * @param context
     * @param token
     * @return
     */
    public static boolean saveTokenMes(Context context, String token) {
        SharedPreferences msp = context.getSharedPreferences(USER, Context.MODE_PRIVATE);
        //获取到edit对象
        SharedPreferences.Editor edit = msp.edit();
        //通过editor对象写入数据
        edit.putString(TOKEN,token);

        //提交数据存入到xml文件中
        boolean result = edit.commit();
        return result;
    }

    /**
     * 获取token
     * @param context
     * @return
     */
    public static String getToken(Context context) {
        SharedPreferences msp = context.getSharedPreferences(USER, Context.MODE_PRIVATE);
        String token = msp.getString(TOKEN,"");
        return token;
    }

    public synchronized static UserInfo getUser() {
        if (instances == null) {
            return new UserInfo();
        }
        if (instances.user == null)
            instances.user = SharedPreferencesHelper.loadFormSource(instances.application, UserInfo.class);
        if (instances.user == null)
            instances.user = new UserInfo();
        return instances.user;
    }

    public static boolean updateUserCache(UserInfo user) {
        if (user == null)
            return false;
        instances.user = user;
        return SharedPreferencesHelper.save(instances.application, user);
    }


    /**
     * 清除用户缓存
     */
    private static void clearUserCache() {
        instances.user = null;
        SharedPreferencesHelper.remove(instances.application, UserInfo.class);
    }

    public static boolean login(final UserInfo user) {
                int count = 10;
        boolean saveOk;
        // 保存缓存
        while (!(saveOk = updateUserCache(user)) && count-- > 0) {
            SystemClock.sleep(100);
        }

        if (saveOk) {
            // 登录成功
        }
        return saveOk;
    }


}
